<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Canvas</title>
    <style type="text/css">
        body {
            text-align: center;
            padding-top: 20px;
        }
        canvas {
            box-shadow: 0 0 10px #333;
            margin: 0 auto;
        }
    </style>
</head>
<body onload="draw()">
<canvas id="canvas" width="1200" height="600">
    你的浏览器太 low 了，请更新~!
</canvas>

<script>
    function draw() {
        var canvas = document.getElementById("canvas");
        if (canvas.getContext) {
            var ctx = canvas.getContext('2d');

            var x = 0;

            // 水平背景移动
            function backgroundMove() {
                // 记录状态
                ctx.save();
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.translate(-x, 0);
                ctx.drawImage(bgImage, 0, 0);
                ctx.drawImage(bgImage, canvas.width, 0);

                // 判断 x 的偏移量
                x ++;
                if (x >= canvas.width) {
                    x = 0;
                }

                ctx.restore();
                window.requestAnimationFrame(backgroundMove);
            }

            var bgImage = new Image();
            bgImage.src = 'img2.jpg';

            bgImage.onload = function () {
                backgroundMove();
            }
        }
    }
</script>
</body>
</html>
